using EFCoreEnterpriseDemo.Data;
using EFCoreEnterpriseDemo.Services;
using Microsoft.EntityFrameworkCore;
using System;

namespace EFCoreEnterpriseDemo.Configurations
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddEnhancedEfCore(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            var environment = services.BuildServiceProvider().GetRequiredService<IWebHostEnvironment>();

            // 核心服务
            services.AddHttpContextAccessor();
            services.AddScoped<IDataPermissionService, DataPermissionService>();
            services.AddScoped<IAuditService, OptimizedAuditService>();

            // 业务服务
            services.AddScoped<IUserService, UserService>();

            // 数据库
            services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
            {
                ConfigureDbContext(options, configuration, environment);
            });

            //services.AddDbContextFactory<ApplicationDbContext>(options =>
            //    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContextFactory<ApplicationDbContext>(options =>
                ConfigureDbContext(options, configuration, environment),
                ServiceLifetime.Scoped
            );

            // 批量操作
            services.AddScoped<IDataImportExportService, DataImportExportService>();

            return services;
        }

        // 添加新的配置方法
        private static void ConfigureDbContext(
            DbContextOptionsBuilder options,
            IConfiguration configuration,
            IWebHostEnvironment environment)
        {
            options.UseMySQL(
                configuration.GetConnectionString("DefaultConnection"),
                builder =>
                {
                    //builder.UseRelationalNulls(true);
                    //builder.MaxBatchSize(600);
                    //builder.CommandTimeout(600);
                });

            // 开发环境配置
            if (environment.IsDevelopment())
            {
                options.EnableSensitiveDataLogging(); // 显示参数值
                options.EnableDetailedErrors();       // 详细错误信息
            }
        }
    }
}